﻿var newsStream = function ($) {
    var settings = {
        requestUrl: "/Services/News/LoadNewsByPosition.ashx",
        listElement: undefined
    };

    var data = new Array();

    function formatString(text) {
        if (arguments.length <= 1) {
            return text;
        }
        var tokenCount = arguments.length - 2;
        for (var token = 0; token <= tokenCount; token++) {
            text = text.replace(new RegExp("\\{" + token + "\\}", "gi"),
                                                arguments[token + 1]);
        }
        return text;
    }

    function buildCacheKey(functionName, args) {
        return formatString("{0}_{1}", functionName, args.join("_"));
    }

    function getCache(key) {
        if (data && data.length > 0)
            return data[key];
        return null;
    }

    function setCache(key, value) {
        data[key] = value;
    }

    function execCallback(callback) {
        if (typeof callback == "function")
            callback();
    }

    function loadData(top, topExclusion, zoneId, callback) {
        var cacheKey = buildCacheKey('loadNewsByPosition', [top, topExclusion, zoneId]);
        var result = getCache(cacheKey);
        if (result != null) {
            bindData(result, callback);
            return;
        }
        $.ajax({
            url: settings.requestUrl,
            data: { top: top, topExclusion: topExclusion, zoneId: zoneId },
            dataType: "json",
            success: function (json) {
                setCache(cacheKey, json);
                bindData(json, callback);
            }
        });
    }

    function bindData(json, callback) {
        if (json && json.length > 0) {
            var htmll = '';
            for (var i = 0; i < json.length; i++) {
                var news = json[i];
            }
            $(settings.listElement).children().last().after(html);
            execCallback(callback);
        }
    }

    return {
        init: function (elmt) {

        }
    };
} (jQuery);